package org.jwebuilder.xom;

import static org.jwebuilder.util.Constant.LINE_SEPARATOR;
import static org.jwebuilder.util.Constant.XML_INDENT;

import java.io.Serializable;

import nu.xom.Document;
import nu.xom.Serializer;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.jwebuilder.parsers.XmlPageParser;

public class XmlDocument implements Serializable
{
	private static final long serialVersionUID = 1216486643061708509L;

	private String id;
	private String xmlEncoding;
	private String xml;
	private transient nu.xom.Document document;

	public XmlDocument(String id)
	{
		super();
		this.id = id;
	}

	public XmlDocument(String id, String xmlEncoding, Document document)
	{
		super();
		this.id = id;
		this.xmlEncoding = xmlEncoding;
		setDocument(document);
	}

	public String getId()
	{
		return id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public String getXmlEncoding()
	{
		return xmlEncoding;
	}

	public void setXmlEncoding(String xmlEncoding)
	{
		this.xmlEncoding = xmlEncoding;
	}

	public String getXml()
	{
		return xml;
	}

	public nu.xom.Document getDocument()
	{
		if(this.document == null)
		{
			try
			{
				this.document = XmlPageParser.getXmlBuilder().build(this.xml, null);
			}
			catch (Exception ex)
			{
				throw new RuntimeException(ex);
			}
		}
		return this.document;
	}

	public void setDocument(nu.xom.Document document)
	{
		this.document = document;
		try
		{
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			Serializer outputer = new Serializer(byteArrayOutputStream, this.xmlEncoding);
			outputer.setIndent(XML_INDENT);
			outputer.setLineSeparator(LINE_SEPARATOR);
			outputer.write(this.document);
			this.xml = byteArrayOutputStream.toString(this.xmlEncoding);
			byteArrayOutputStream.close();
			byteArrayOutputStream = null;
			outputer = null;
		}
		catch(Exception ex)
		{
			throw new RuntimeException(ex);
		}
	}

	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final XmlDocument other = (XmlDocument) obj;
		if (id == null)
		{
			if (other.id != null)
				return false;
		}
		else if (!id.equals(other.id))
			return false;
		return true;
	}
}